<?php

namespace App\Admin\Controllers;

use App\Http\Requests\TopicRequest;
use App\Models\Comment;
use App\Models\Forum;
use App\Models\Tag;
use App\Models\Topic;
use Encore\Admin\Http\Controllers\AdminController;
use App\Repositories\TopicRepository;
use App\Rules\TuWenContent;
use App\Models\User;
use Encore\Admin\Form;
use Encore\Admin\Table;
use Encore\Admin\Show;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class TopicController extends AdminController
{
    protected $title = "帖子";


    /**
     * Make a grid builder.
     *
     * @return Table
     */
    protected function table()
    {
        $table = new Table(new Topic);
        $table->model()->with(['user', 'forum', 'mainFloor', 'mainFloor.detail', 'mainFloor.hide', 'stickyInfo'])->withTrashed()->orderBy('id', 'desc');

        $table->id('Id');
        $table->column('类型')->display(function () {
            return $this->typeName;
        });
        $table->column('标题')->display(function () {
            $title = $this->title;
            $stickyInfo = $this->stickyInfo;
            if ($stickyInfo) {
                $title = '[置顶]' . $title;
            }
            return $title;
        });
        $table->column('内容')->display(function () {
            return sprintf('<a target="_blank" href="%s">%s</a>', route('admin.topic.show', [$this->id]),$this->mainFloor->detail_excerpt);
        });
        $table->column('user.username', '作者');
        $table->column('forum.name', '版块');
        $table->view_count('浏览量');
        $table->comment_count('回复数');

        $table->created_at('发表时间');

        $table->column('last_comment_time', '最后回复时间')->display(function ($value) {
            return $value ? date('Y-m-d H:i:s', $value) : "";
        });
        $table->column('状态')->display(function () {
            return $this->trashed() ? '删除' : '正常';
        });

        $table->filter(function ($filters) {
            $filters->equal('fid', '版块')->select(Forum::pluck('name', 'id'));
        });

        return $table;
    }

    /**
     * Make a show builder.
     *
     * @param mixed   $id
     * @return Show
     */
    protected function detail($id)
    {
        $user = auth_user();
        $topic = Topic::query()->with(['tags', 'lastOperationLog', 'lastOperationLog.user'])->withTrashed()->findOrFail($id);
        $with = [
            'user', 'detail', 'hide',
            'firstComments', 'firstComments.user', 'firstComments.detail',
            'firstComments.parentComment', 'firstComments.parentComment.user',
        ];
        $list = Comment::query()->where('tid', $id)
            ->where('pid', 0)
            ->withTrashed()
            ->with($with)
            ->orderBy('id', 'asc')
            ->paginate(Topic::DETAIL_COMMENT_PAGE_SIZE);

        return view('admin.topic.show', compact('topic','list', 'user'));
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Topic);

        $form->text('title', '标题');
        $form->select('uid', '发表用户')->options(function ($id) {
            $user = User::query()->find($id);
            if ($user) {
                return [$user->id => $user->name];
            }
        })->ajax(route('admin.user.search'));
        $form->select('fid', '版块')->options(Forum::query()->pluck('name', 'id'))->rules('required|exists:forums,id');
        $form->radio('type', '类型')->options(Topic::$types)->when(Topic::TYPE_REPORT, function (Form $form) {
            $form->datetime('action_time', '出击时间');
            $form->text('action_location', '出击地点');
            $form->latlong('latitude', 'longitude', '地点位置');
        })->default(Topic::TYPE_GENERAL);

        $form->editing(function ($form) {
            $model = $form->model();
            $comment = $model->mainFloor;
            $detail = $comment->detail;
            $model->content_detail = json_encode($detail->content);

            $hide = $comment->hide;
            if ($hide) {
                $model->content_hide = json_encode($hide->content);
                $model->has_hide = 1;
                $model->require_reply = $hide->require_reply;
                $model->require_score = $hide->require_score;
            }

            $model->forum_key = $model->forum->key;
        });
        $form->content('content_detail', '内容详情')->rules(['required', new TuWenContent()]);

        $form->radio('has_hide', '是否有隐藏部分')->options([0 => '无', 1 => '有'])
            ->when(1, function ($form) {
                $form->content('content_hide', '隐藏部分内容');
                $form->radio('require_reply', '隐藏部分回复可见')->options([0 => '不需要', 1 => '需要'])->default(0);
                $form->number('require_score', '隐藏部分积分高于多少可见');
            })->default(0);

        $form->checkbox('tags', '标签')->options(Tag::query()->pluck('name', 'id'));


        return $form;
    }

    public function store()
    {
        $request = request();
        if ($validationMessages = $this->form()->validationMessages($request->all())) {
            return back()->withInput()->withErrors($validationMessages);
        }

        $result = (new TopicRepository())->create($request, User::first());

        if ($request->wantsJson()) {
            return $result;
        } else {
            if ($result['ret'] == 0) {
                return redirect()->route('admin.topic.index');
            } else {
                $error = new MessageBag(['title' => '发生错误', 'message' => $result['msg']]);
                return back()->with(compact('error'));
            }
        }

    }

    public function update($id)
    {
        $request = request();
        if ($validationMessages = $this->form()->validationMessages($request->all())) {
            return back()->withInput()->withErrors($validationMessages);
        }

        $result = (new TopicRepository())->update($request, $id);

        if ($result['ret'] == 0) {
            return redirect()->route('admin.topic.index');
        } else {
            $error = new MessageBag(['title' => '发生错误', 'message' => $result['msg']]);
            return back()->with(compact('error'));
        }
    }

    public function changeSensitivity(TopicRequest $request)
    {
        $result = (new TopicRepository())->changeSensitivity($request->tid, $request->sensitivity);

        if ($result) {
            return api(RET_OK, MSG_OK, []);
        }

        return api('更新失败');
    }

    public function toggleSticky(TopicRequest $request)
    {
        $result = (new TopicRepository())->toggleSticky($request->tid, $request->is_sticky);

        if ($result) {
            return api(RET_OK, MSG_OK, []);
        }

        return api('更新失败');
    }
}
